<template>
	<u-popup :show="visible" round="16rpx" mode="bottom" @close="hide">
		<view class="add-photo">
			<view class="add-photo__head">
				<text>上传相册</text>
				<view class="add-photo__head-close bg-hover" @tap="hide">
					<u-image width="32rpx" height="32rpx"
						src="https://file.casugn.com/storecompcard/static/img/tips／close@2x_1681978220794.png"></u-image>
				</view>
			</view>
			<view class="add-photo__form">
				<u-form ref="uForm" :model="model" :rules="rules">
					<u-form-item prop="urlList" labelPosition="top" borderBottom>
						<u-upload name="Wx" :fileList="fileListWx" :maxCount="9" multiple width="218rpx" height="218rpx"
							@afterRead="afterRead" @delete="deletePic">
							<view class="upload-box">
								<u-icon name="plus" color="#C9CDD4" size="64rpx"></u-icon>
								<text class="upload-text">点击上传</text>
							</view>
						</u-upload>
					</u-form-item>
					<u-form-item prop="context" label="备注" labelWidth="100" labelAlign="left" labelPosition="left" borderBottom>
						<u-input v-model="model.context" border="none" placeholder="请输入备注"
							:customStyle="inputCustomStyle"></u-input>
					</u-form-item>
				</u-form>
			</view>

			<view class="submit-box">
				<u-button color="#276AEE" text="上传" throttleTime="500" @click="submit"></u-button>
			</view>
		</view>
	</u-popup>
</template>

<script>
	import { mapGetters } from 'vuex'
	import baseConfig from '@/config/baseUrl.js'

	export default {
		options: {
			styleIsolation: 'shared', // 解除样式隔离
		},
		props: {
			albumId: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				inputCustomStyle: { padding: '10rpx 0' },
				visible: false,
				rules: {
					urlList: [{
						required: true,
						type: Array,
						message: '请选择照片',
						trigger: ['blur', 'change'],
						validator: (rule, value, callback) => {
							if (!value || !value.length) {
								callback(new Error("请选择照片"))
							} else {
								callback()
							}
						}
					}],
				},
				model: {
					urlList: '',
					context: '',
				},
				fileListWx: [],

				loading: false,
			}
		},
		computed: {
			...mapGetters(['openId']),
		},
		watch: {
			fileListWx: {
				handler(nVal, oVal) {
					if ((!nVal || !nVal.length) && (!oVal || !oVal.length)) {
						return
					}
					let tFilter = nVal.filter(item => item.status === 'success')
					this.$set(this.model, 'urlList', tFilter.map(item => item.url))

					if (tFilter.length === nVal.length) {
						this.$refs.uForm.validateField(['urlList'])
					}
				},
				deep: true
			}
		},
		methods: {
			show() {
				this.visible = true
				this.fileListWx = []
				for (let key of Object.keys(this.model)) {
					// console.log(key);
					this.$set(this.model, key, '')
				}

				this.$nextTick(() => {
					this.$refs.uForm.setRules(this.rules)
					this.$refs.uForm.resetFields()
					this.$refs.uForm.clearValidate(['urlList', 'context'])
				})
			},
			hide() {
				this.visible = false
			},
			submit() {
				const that = this
				this.loading = true
				this.$refs.uForm.validate().then(async success => {
					let params = {
						...that.model,
						albumId: that.albumId,
						createBy: that.openId,
						isDel: 0,
					}
					console.log(params);
					let res = await that.$api.addAlbumPhoto(params)
					that.loading = false
					if (res.success) {
						uni.showToast({ title: '提交成功！', icon: 'none' });
						that.hide()
						that.$emit('refresh')
					} else {
						uni.showToast({ title: res.message || '提交失败！', icon: 'none' });
					}
				}).catch(errors => {
					uni.$u.toast('校验失败')
					that.loading = false
				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				console.log('新增图片', event);
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: event.name,
						url: result,
						fileName: event.file[0].type + event.file[0].size + '',
						filePath: result,
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: baseConfig.uploadUrl + '/sys/common/upload',
						filePath: url,
						name: 'file',
						success: (res) => {
							let data = JSON.parse(res.data)
							if (data.success) {
								resolve(data.message)
							}
						}
					});
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.add-photo {

		.add-photo__head {
			position: relative;
			height: 92rpx;
			font-size: 32rpx;
			font-weight: 600;
			color: #1D2129;
			line-height: 44rpx;

			display: flex;
			justify-content: center;
			align-items: center;

			.add-photo__head-close {
				position: absolute;
				top: 30rpx;
				right: 32rpx;
			}
		}

		::v-deep.add-photo__form {
			padding: 24rpx 32rpx;

			.u-form-item__body__left__content__required {
				position: relative !important;
				left: 0 !important;
				padding-right: 10rpx !important;
			}
		}

		::v-deep.u-upload {

			.u-upload__deletable {
				width: 32rpx !important;
				height: 32rpx !important;

				.uicon-close {
					font-size: 24rpx !important;
					line-height: 24rpx !important;
				}
			}

			.u-upload__success {
				.u-upload__success__icon .uicon-checkmark {
					font-size: 28rpx !important;
					line-height: 32rpx !important;
				}
			}

			.u-upload__wrap__preview:nth-child(3n+3) {
				margin-right: 0;
			}
		}

		.upload-box {
			width: 218rpx;
			height: 218rpx;
			background-color: #F7F8FA;
			border-radius: 4rpx;

			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;

			.upload-text {
				margin-top: 6rpx;
				font-size: 24rpx;
				color: #86909C;
				line-height: 34rpx;
			}
		}

		.submit-box {
			padding: 0 32rpx 40rpx;
		}
	}
</style>
